package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDim;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dim.function.DimSinkFunction;
import com.atguigu.gmall.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

/**
 * @author Felix
 * @date 2024/6/18
 * Dim层处理
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、DimApp
 * 开发流程
 *      基本环境准备
 *      检查点设置
 *      从kafka的topic_db主题中读取数据
 *      对读取到的数据进行类型转化   jsonStr->jsonObj
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *      使用FlinkCDC从配置表中读取配置信息---配置流
 *      对配置流进行类型转换  jsonStr->实体类对象
 *      根据配置信息到HBase中执行建表以及删表操作
 *          op='d' 删表
 *          op='c'|'r' 建表
 *          op='u' 先删表再建表
 *      广播配置流---broadcast
 *      将主流和广播流进行关联---connect
 *      对关联后的数据进行处理---process
 *          class TableProcessFunction extends BroadProcessFunction{
 *              open:将配置表中配置信息预加载到程序的configMap中
 *              processElement:对主流数据进行处理
 *                  根据表名从广播状态以及configMap中获取对应的配置信息，如果配置信息不为空，说明是维度数据，传递到下游
 *                  格式:Tuple2  f0:dataJsonObj   f1:TableProcessDim
 *                  在向下游传递数据前，过滤掉了不需要传递的属性
 *                  在向下游传递数据前，补充type类型
 *              processBroadcastElement:对广播流数据进行处理
 *                  op='d'  从广播状态以及configMap中删除对应的配置信息
 *                  op!='d' 向广播状态以及configMap中put对应的配置信息
 *          }
 *     将流中数据同步到HBase对应的表中
 *          class DimSinkFunction extends RichSinkFunction{
 *              invoke:
 *                  type='delete'  :从HBase表中删除数据
 *                  type!='delete' :向HBase表中put数据
 *          }
 * 执行流程（以对品牌维度表进行修改为例说明）
 *      当DimApp应用程序启动的时候，会将配置表中的配置信息加载到ConfigMap以及广播状态中
 *      当对品牌维度表进行修改操作后，binlog会记录变化
 *      maxwell会从binlog中读取变化数据，并封装为json格式字符串，发送到topic_db主题中
 *      DimApp从topic_db主题中读取数据，并对其进行处理
 *          根据表名从广播状态以及ConfigMap中获取配置信息
 *          ....
 *
 */
public class DimApp extends BaseApp {
    public static void main(String[] args) {
       new DimApp().start(10002,4,"dim_app",Constant.TOPIC_DB);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //TODO 对流中数据进行类型转换并进行简单的ETL        jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = etl(kafkaStrDS);

        //TODO 使用FlinkCDC读取配置表中的配置信息
        SingleOutputStreamOperator<TableProcessDim> tpDS = readTableProcess(env);

        //TODO 根据读取到的配置信息 在HBase中建表或者删表
        tpDS = createHBaseTable(tpDS);

        //TODO 对配置流进行广播           ---broadcast  将主流和广播流进行关联      ---connect  对关联后的数据进行处理（过滤出维度数据）---process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connect(tpDS, jsonObjDS);

        //TODO 将维度数据同步到HBase对应的表中
        writeToHBase(dimDS);
    }

    private static void writeToHBase(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS) {
        //f0: {"tm_name":"Redmi123","id":1,"type":"update"}
        //f1: TableProcessDim(sourceTable=base_trademark, sinkTable=dim_base_trademark, sinkColumns=id,tm_name, sinkFamily=info, sinkRowKey=id, op=r)
        dimDS.print();
        dimDS.addSink(
                new DimSinkFunction()
        );
    }

    private static SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<TableProcessDim> tpDS, SingleOutputStreamOperator<JSONObject> jsonObjDS) {
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcessDim>("mapStateDescriptor",String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = tpDS.broadcast(mapStateDescriptor);


        BroadcastConnectedStream<JSONObject, TableProcessDim> connectDS = jsonObjDS.connect(broadcastDS);


        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );
        return dimDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> createHBaseTable(SingleOutputStreamOperator<TableProcessDim> tpDS) {
        tpDS = tpDS.map(
                new RichMapFunction<TableProcessDim, TableProcessDim>() {
                    private Connection hBaseConn;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hBaseConn = HBaseUtil.getHBaseConnection();
                    }

                    @Override
                    public void close() throws Exception {
                        HBaseUtil.closeHBaseConnection(hBaseConn);
                    }

                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        //获取对配置表进行的操作的类型
                        String op = tableProcessDim.getOp();
                        //获取要操作的HBase表的表名
                        String sinkTable = tableProcessDim.getSinkTable();
                        //获取Hbase中维度表的列族
                        String[] sinkFamilies = tableProcessDim.getSinkFamily().split(",");
                        if("d".equals(op)){
                            //从配置表中删除了一条数据  将这条配置信息对应的维度表从Hbase中删除掉
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                        }else if("r".equals(op)||"c".equals(op)){
                            //从配置表中读取了一条配置或者向配置表中添加了一条配置  在HBase中创建对应的维度表
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,sinkFamilies);
                        }else {
                            //对配置表进行的更新操作
                            //先从HBase中删除对应的维度表
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                            //再创建
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,sinkFamilies);
                        }
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);
        //tpDS.print("~~~~~>>");
        return tpDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> readTableProcess(StreamExecutionEnvironment env) {
        //创建MySqlSource
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("gmall1226_config", "table_process_dim");
        //读取数据 封装为流
        DataStreamSource<String> mysqlStrDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);
        //{"before":null,"after":{"source_table":"base_region","sink_table":"dim_base_region","sink_family":"info","sink_columns":"id,region_name","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall1226_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1718760416135,"transaction":null}
        //{"before":null,"after":{"source_table":"t_a","sink_table":"dim_t_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1718760531000,"snapshot":"false","db":"gmall1226_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":412,"row":0,"thread":8,"query":null},"op":"c","ts_ms":1718760531244,"transaction":null}
        //{"before":{"source_table":"t_a","sink_table":"dim_t_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"t_a","sink_table":"dim_t_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1718760550000,"snapshot":"false","db":"gmall1226_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":776,"row":0,"thread":8,"query":null},"op":"u","ts_ms":1718760550395,"transaction":null}
        //{"before":{"source_table":"t_a","sink_table":"dim_t_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1718760576000,"snapshot":"false","db":"gmall1226_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":1170,"row":0,"thread":8,"query":null},"op":"d","ts_ms":1718760576265,"transaction":null}

        //mysqlStrDS.print();


        //对配置流中的数据 进行类型转换    jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcessDim> tpDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(String jsonStr) throws Exception {
                        //为了处理方便，先将jsonStr转换为jsonObj
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        //获取对配置表进行的操作的类型
                        String op = jsonObj.getString("op");
                        TableProcessDim tableProcessDim = null;
                        if ("d".equals(op)) {
                            //说明从配置表中删除了一条配置信息，需要从before属性中获取删除前的配置
                            tableProcessDim = jsonObj.getObject("before", TableProcessDim.class);
                        } else {
                            //说明对配置表做了读取、更新、添加操作，这些从做都需要从after属性中获取对应的配置信息
                            tableProcessDim = jsonObj.getObject("after", TableProcessDim.class);
                        }

                        tableProcessDim.setOp(op);

                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);

        //tpDS.print();
        return tpDS;
    }

    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaStrDS) {
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            String db = jsonObj.getString("database");
                            String type = jsonObj.getString("type");
                            String data = jsonObj.getString("data");

                            if ("gmall1226".equals(db)
                                    && ("insert".equals(type)
                                    || "update".equals(type)
                                    || "delete".equals(type)
                                    || "bootstrap-insert".equals(type))
                                    && data != null
                                    && data.length() > 2) {
                                out.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("不是一个标准的json");
                        }

                    }
                }
        );
        //jsonObjDS.print();
        return jsonObjDS;
    }
}